<template>
  <el-dialog
    v-model="studentDrawer"
    :title="drawTitle"
    size="450px"
    class="enterprise-drawer"
  >
    <template #default>
      <el-form ref="userFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="学员名称" prop="realName">
          <el-input v-model="formData.realName" placeholder="请输入学员名称" />
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <div class="form-img" @click="handleUpload">
            <div class="has-img" v-if="formData.avatar">
              <img :src="formData.avatar" alt="">
              <span > 
                <el-icon @click.stop="handleRemoveImg"><Delete /></el-icon>
              </span>
            </div>
            <el-icon v-else>
              <Plus />
            </el-icon>
          </div>
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="formData.name" placeholder="请输入学员昵称" />
        </el-form-item>
        <el-form-item label="手机号" prop="account">
          <el-input v-model="formData.account" placeholder="请输入手机号" />
        </el-form-item>
        <!-- <el-form-item label="身份证号" prop="identificationNumber">
          <el-input v-model="formData.identificationNumber" placeholder="请输入身份证号" />
        </el-form-item> -->
        <!-- 选择部门  -->
        <!-- <el-form-item label="选择部门" prop="permanent">
          <el-cascader :options="departTree" v-model="formData.departId" clearable :show-all-levels="false" popper-class="pid-cascader" placeholder="请选择部门" @change="handleChange">
            <template #default="{ data }">
              <p>{{data.label}}</p>
            </template>
          </el-cascader>
        </el-form-item> -->
        <!-- 选择分组  -->
        <!-- <el-form-item label="选择分组" prop="permanent">
          <el-select
            v-model="formData.groupId"
            style="width: 200px"
            @change="handleReplyChange"
          >
            <el-option
              v-for="item in groupList"
              :key="item.value"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item label="入职时间" prop="joinTime" >
          <el-date-picker 
            v-model="formData.joinTime"
            type="datetime"
            placeholder="选择入职时间"
          />
        </el-form-item> -->
        <el-form-item label="密码" prop="password">
          <el-button @click="resetPassword" v-show="!isResetPass && userFormWay !== 1">重置密码</el-button>
          <el-input v-model="formData.password" readonly v-show="isResetPass || userFormWay === 1">
            <template #append v-if="userFormWay !== 1">
              <div class="done-reset-password" v-if="isResetPass">
                <i class="iconfont">&#xe655;</i>
                已重置
              </div>
            </template>
            <template #append v-else>
              <div class="reset-password" @click="initPassword" v-if="!isInitPass">生成密码</div>
              <div class="done-reset-password" v-if="isInitPass">
                <i class="iconfont">&#xe655;</i>
                已生成
              </div>
            </template>
          </el-input>
        </el-form-item>
        <!-- <el-form-item label="是否长期有效" prop="permanent">
          <el-switch v-model="formData.permanent" />
        </el-form-item>
        <el-form-item label="有效时间" prop="effectiveTime" >
          <el-date-picker 
            v-model="formData.effectiveTime"
            type="effectiveTime"
            placeholder="选择有效时间"
          />
        </el-form-item> -->
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="studentDrawer = false">取消</el-button>
        <el-button type="primary" @click="confirmClick">确认</el-button>
      </div>
    </template>
  </el-dialog>
  <FilesUpload v-if="showFilesUpload" v-model:showDialog="showFilesUpload" :isPublic="true" @getFileList="insertFiles" :isToJpg="true" :limit="10"></FilesUpload>

</template>
<script setup>
  import { ref, reactive, onMounted, computed } from 'vue'
  import { formatDate } from '@/utils/tools'
  import { getUserInfo, saveUserUser, getUserInfoWithoutDesensitize } from "@/api/student"
  import { ElMessage } from 'element-plus'
  import { getDepartTree } from "@/api/depart";
  import { pagingGroup } from "@/api/group";
  import { useStore } from 'vuex' 
  import { FilesUpload } from "@ruifox-cms/components"
  import { Plus, Delete } from '@element-plus/icons-vue'

  const props = defineProps({
    modelValue: { // 必须使用 modelValue 作为 prop 名称
      type: Boolean,
      default: false
    },
    // 其他需要的props...
  });

  const emit = defineEmits(['update:modelValue']);
  const studentDrawer = computed({
    get() {
      return props.modelValue;
    },
    set(value) {
      emit('update:modelValue', value);
    }
  });
  const store = useStore();
 
  const rules = {
    realName: [{ required: true, message: '请输入学员姓名', trigger: 'blur' }],
    account: [
      { required: true, message: '请输入学员手机号', trigger: 'blur' },
      { 
        pattern: /^1[3-9]\d{9}$/, 
        message: '请输入正确的手机号格式', 
        trigger: 'blur' 
      }
    ],
    identificationNumber: [
      { required: true, message: '请输入学员身份证', trigger: 'blur' },
      { 
        pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, 
        message: '请输入正确的身份证号码', 
        trigger: 'blur' 
      }
    ],
    // joinTime: [{ required: true, message: '请选择学员入职时间', trigger: 'change' }],
  }
  //保存用户
  const delaultStudent = reactive({
    id: "",
    pid: 0,
    account: "",
    password: "",
    name: "",
    introduction: "",
    avatar: "",
    appKey: "",
    appSecret: "",
    mfa: 0,
    fce: 0,
    validTime: "",
    state: 0,
    groupId: store.state.base.userInfo.groupId,
    realName: "",
    identificationNumber: "",
    identificationPhoto: "",
    identificationVerify: true,
    departId: "",
    joinTime: "",
    permanent: true,
    effectiveTime: "",
    updateMainUserInfo: true,
    cohortIds: []
  })
  const formData = ref(delaultStudent)
  
  // const studentDrawer = ref(false);
  const drawTitle = ref("");
  //编辑
  const showDrawer = async () => {
    drawTitle.value = "个人信息修改";
    // studentDrawer.value = true;
    // formData.value = {...row};
    console.log("formData.value00",formData.value);
  
    if(formData.value.joinTime && formData.value.joinTime != ""){
      formData.value.joinTime = formData.value.joinTime.replace(' ', 'T');
    }
    //根据用户请求详细数据
    const res = await getUserInfoWithoutDesensitize({userId: formData.value.id})
    if(res.code === 20000){
      formData.value.realName = res.data.realName
      formData.value.identificationNumber = res.data.identificationNumber
    }
    console.log("formData.value",formData.value);
  };
  
  //用户头像 附件上传
  const showFilesUpload = ref(false)
  const resourceFormList = ref([])
  const fileName = ref("")
  const fileUrl = ref("")
  const insertFiles = (filesList,res) => {
    console.log("filesList",filesList);
    console.log("res",res);
    
    resourceFormList.value = filesList.map(item => {
      return {
        resourceData: {
          title: item.name,
          url: item.url,
          uid: item.uid,
        },
        needUpload: item.needUpload,
        tagList: item.tagList || [],
      }
    })
    console.log("resourceFormList.value",resourceFormList.value);
    fileName.value = resourceFormList.value[0].resourceData.title
    fileUrl.value = resourceFormList.value[0].resourceData.url
    formData.value.avatar = resourceFormList.value[0].resourceData.url
  }

  // 预览缩略图
  // const thumbDialog = ref(false)
  // const handlePreviewThumb = () => {
  //   thumbDialog.value = true
  // }
  const handleUpload = () => {
    showFilesUpload.value = true
  }
  // 移除缩略图
  const handleRemoveImg = () => {
    formData.value.avatar = ''
  }

  //提交用户
  const userFormRef = ref(null);
  const confirmClick = async () => {
    // 校验表单
    if (!userFormRef.value) return;
    try {
      const valid = await validateForm();
      if (!valid) return;
      if(formData.value.joinTime){
        formData.value.joinTime = formatDate(formData.value.joinTime, "YYYY-MM-DD HH:mm:ss");
      }
      if(formData.value.effectiveTime){
        formData.value.effectiveTime = formatDate(formData.value.effectiveTime, "YYYY-MM-DD HH:mm:ss");
      }
      if(formData.value.departId && formData.value.departId != "")
      if (Array.isArray(formData.value.departId)) {
        formData.value.departId = formData.value.departId[formData.value.departId.length - 1]
      }
      //根据标题判断是添加还是修改
      const res = await saveUserUser(formData.value)
      if (res.code === 20000) {
        ElMessage.success("修改成功");
        getUserData()
      }
      studentDrawer.value = false;
      isResetPass.value = false;
    } catch (error) {
      console.error("An error occurred:", error);
    }
  };
  
  //检查表单
  const validateForm = () => {
    return new Promise((resolve) => {
      userFormRef.value.validate((isValid, fields) => {
        if (isValid) {
          console.log("submit!");
          resolve(true);
        } else {
          console.log("error submit!", fields);
          resolve(false);
        }
      });
    });
  };
  
  //重置密码
  const isResetPass = ref(false)
  const isInitPass = ref(false)
  
  const resetPassword = () => {
    isResetPass.value = true
    formData.value.send_note = true
    formData.value.password = generatePassword(10)
    if (rules.value) {
      rules.value.validateField('password')
    }
  }
  const initPassword = () => {
    isInitPass.value = true
    formData.value.send_note = true
    formData.value.password = generatePassword(10)
    if (rules.value) {
      rules.value.validateField('password')
    }
  }
  const generatePassword = (length) => {
    const lowercase = 'abcdefghijklmnopqrstuvwxyz'
    const uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    const numbers = '0123456789'
    const special = '!@#$%^&*'
    
    // 所有可用字符
    const allChars = lowercase + uppercase + numbers + special
    
    // 确保至少包含三种字符类型
    let password = ''
    const charTypes = [lowercase, uppercase, numbers, special]
    
    // 随机选择3种字符类型
    const selectedTypes = charTypes
      .sort(() => Math.random() - 0.5)
      .slice(0, 3)
    
    // 从每种选中的类型中至少选择一个字符
    selectedTypes.forEach(type => {
      password += type.charAt(Math.floor(Math.random() * type.length))
    })
    
    // 填充剩余长度
    while (password.length < length) {
      password += allChars.charAt(Math.floor(Math.random() * allChars.length))
    }
  
    return password
      .split('')
      .sort(() => Math.random() - 0.5)
      .join('')
  }
  
  //获取部门树
  const departTree = ref([]);
  const transformData = (data) => {
    return data.map(item => {
      const transformedItem = {
        value: item.id,
        label: item.name
      };
  
      if (item.children && item.children.length > 0) {
        transformedItem.children = transformData(item.children);
      }
  
      return transformedItem;
    });
  };
  const getDepartData = async () => {
    const res = await getDepartTree({departId: "root"});
    if (res.code === 20000) {
      departTree.value = transformData(res.data.children)
    }
  };
  
  // const theDepartId = ref("");
  
  //获取分组
  const groupList = ref([])
  // const theGroup = ref("");
  const getGroupData = async () => {
    const res = await pagingGroup({ 
      currentPage: 1,
      pageSize: 100
    });
    groupList.value = res.data.list;
    // let newList = groupList.value.map(item => ({
    //     value: item.id,
    //     label: item.name,
    //   }));
    // searchCmpArray.value[2].options = newList
  };
  
  //获取用户信息
  const getUserData = async () => {
    const res = await getUserInfo();
    console.log("用户信息",res);
    //因为getUserInfo返回数据和保存用户数据格式不一样，手动更改数据
    // formData.value = res.data;
    formData.value.account = res.data.account;
    formData.value.avatar = res.data.avatar;
    formData.value.password = res.data.password;
    formData.value.name = res.data.name;
    formData.value.realName = res.data.realName;
    formData.value.departId = res.data.departId;
    formData.value.id = res.data.id;
  };
  // beforeMounted(() => {
  //   getDepartData();
  // });
  onMounted(async() => {
    await getUserData();
    await getDepartData();
    await getGroupData();
    await showDrawer();
  });
</script>
<style scoped lang="scss">
.form-img {
  height: 100px;
  width: 150px;
  border: 1px dashed $borderColor;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;

  .has-img {
    height: 100%;
    width: 100%;
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;

    img {
      max-width: 100%;
      max-height: 100%;
    }

    span {
      display: none;
      position: absolute;
      right: 0;
      top: 0;
      background-color: $failColor;
      height: 20px;
      width: 20px;
      font-size: 18px;
      color: #fff;
    }

    &:hover {
      span {
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
}
</style>